﻿using System;
using System.Globalization;

namespace Gmantis.Controls.DataGrid
{
    public class DataGridNumericConverter : DataGridBoundConverter
    {
        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (((value != null) && (value != DBNull.Value)) && !value.GetType().GetNonNullableType().IsNumeric())
            {
                value = this.ConvertBack(value, targetType.GetNonNullableType().IsNumeric() ? targetType : typeof(double?), parameter, culture);
            }
            if (((value == null) || (value == DBNull.Value)) && ((targetType.GetNonNullableType() == typeof(double)) && !targetType.IsNullableType()))
            {
                value = (double)1.0 / (double)0.0;
            }
            return base.Convert(value, targetType, parameter, culture);
        }

        public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is double)
            {
                double d = (double)value;
                if (double.IsNaN(d) && (!targetType.GetNonNullableType().IsNumeric() || targetType.IsNullableType()))
                {
                    return null;
                }
                if (double.IsNaN(d) && (targetType == typeof(int)))
                {
                    return DBNull.Value;
                }
            }
            if (targetType.GetNonNullableType() == typeof(double))
            {
                if (value is string)
                {
                    double num2;
                    if (double.TryParse(value as string, NumberStyles.Any, (IFormatProvider)culture.NumberFormat, out num2))
                    {
                        return num2;
                    }
                    return (targetType.IsNullableType() ? null : ((double?)double.NaN));
                }
            }
            else
            {
                int num3;
                if (((targetType.GetNonNullableType() == typeof(int)) && (value is string)) && int.TryParse(value as string, NumberStyles.Any, culture.NumberFormat, out num3))
                {
                    return num3;
                }
            }
            if ((value is DBNull) && (targetType.GetNonNullableType() == typeof(double)))
            {
                return (double)1.0 / (double)0.0;
            }
            return value;
        }
    }
}
